<template>
  <div class="player" v-show="playList.length > 0" ref="play">
    <transition name='normal'
                @enter='enter'
                @after-enter='afterEnter'
                @leave='leave'
                @after-leave='afterLeave'
    >
     <div class="normal-player " v-show="fullScreen">
       <div class="background">
         <img :src="currentSong.image" width="100%" height="100%" alt="">
       </div>
       <div class="top">
         <div class="back" @click="toMiniPlayer">
           <i class="icon-back"></i>
         </div>
          <h1 class="title" v-html="currentSong.name"></h1>
          <h2 class="subtitle" v-html="currentSong.singer"></h2>
       </div>
       <div class="middle" 
          @touchstart.prevent='middleTouchStart'
          @touchmove.prevent='middleTouchMove'
          @touchend='middleTouchEnd'
       >
         <div class="middle-l" ref='middleCD'>
           <div class="cd-wrapper" ref="cdWrapper">
             <div class="cd" :class="cdCls">
               <img alt="" class="image" :src="currentSong.image">
             </div>
           </div>
           <div class="playing-lyric-wrapper">
             <div class="playing-lyric">{{playingLyric}}</div>
           </div>
         </div>
         <scroll class='middle-r' ref='lyricList' :data='currentLyric && currentLyric.lines'>
           <div class="lyric-wrapper" >
             <div v-if="currentLyric" >
               <p 
                ref="lyricLine"
                class="text"
                :class="{'current': currentLineNum===index}"
                v-for="(line,index) of currentLyric.lines" :key="index"
               >{{line.txt}}</p>
             </div>
           </div>
         </scroll>
       </div>
       <div class="bottom">
         <div class="dot-wrapper">
           <div class="dot" :class="{'active': currentShow==='cd'}"></div>
           <div class="dot" :class="{'active': currentShow==='lyric'}"></div>
         </div>
         <div class="progress-wrapper">
          <div class="time time-l">{{formatTime(currentTime)}}</div>
          <div class="progress-bar-wrapper">
            <progress-bar 
              @slidingTimeChange='slidingTimeChange'
              :precent='precent'
              @barStatus='barPrecent'
            ></progress-bar>
          </div>
          <span class="time time-r">{{formatTime(currentSong.duration)}}</span>
         </div>
         <div class="operators">
           <div class="icon i-left" @click="changeMode">
             <i :class="iconMode" ></i>
           </div>
           <div class="icon i-left" :class="disable">
             <i class="icon-prev" @click="prev"></i>
           </div>
           <div class="icon i-center" :class="disable">
             <i :class="playicon" @click="togglePlaying"></i>
           </div>
           <div class="icon i-right" :class="disable">
             <i class="icon-next" @click="next"></i>
           </div>
           <div class="icon i-right">
             <i class="icon" 
              :class="setFavoriteIcon(currentSong)"
              @click="getFavoriteState(currentSong)"
             ></i>
           </div>
         </div>
       </div>
     </div>
     </transition>
     <transition name='mini'>
     <div class="mini-player" v-show="!fullScreen" @click="toMaxPlayer">
        <div class="icon" >
          <img :class="cdCls" width="40" height="40" alt="" :src="currentSong.image">
        </div>
        <div class="text">
          <h2 class="name" v-html="currentSong.name"></h2>
          <p class="desc" v-html="currentSong.singer"></p>
        </div>
        <div class="control">
          <progress-circle :radius='radius' :precent='precent'>
            <i  @click.stop='togglePlaying' class="icon-mini" :class='miniPlayicon'></i>
          </progress-circle>
        </div>
        <div class="control" @click.stop="showPlayList">
          <i class="icon-playlist"></i>
          </div>
     </div>
     </transition>
     <play-list ref="playList" ></play-list>
     <audio 
          :src="currentSong.url" 
          ref="audio"
          @canplay="ready" 
          @error="error"
          @timeupdate='updateTime'
          @ended="songEnded"
      ></audio>
      
  </div>
</template>

<script type="text/ecmascript-6">
 import { mapGetters,mapActions } from 'vuex'
 import animations from 'create-keyframe-animation'
 import {prefixStyle} from 'common/js/dom'
 import progressBar from 'base/progress-bar/progress-bar'
 import progressCircle from 'base/progress-circle/progress-circle'
 import {playMode} from 'common/js/config'
 import {shuffle} from 'common/js/util'
 import Lyric from 'lyric-parser'
 import Scroll  from 'base/scroll/scroll'
 import PlayList from 'components/playlist/playlist'
 import {playerMixin} from 'common/js/mixin'
 

 const transform= prefixStyle('transform')
 const transitionDuration= prefixStyle('transitionDuration')

export default {
    components:{
      progressBar,
      progressCircle,
      Scroll,
      PlayList
    },
    created() {
      this.touch={}
    },
    mixins: [playerMixin],
    data() {
      return {
        playReady: false,
        currentTime: 0,
        radius: 32,
        currentLyric: null,
        currentLineNum: 0,
        currentShow: 'cd',
        playingLyric: ''
      }
    },
    computed: {
      ...mapGetters([
        'fullScreen',
        'playing',
        'currentIndex',
      ]),
      //播放按钮样式
      playicon(){
        return this.playing ? 'icon-pause' : 'icon-play'
      },
      //mini播放器按钮样式
      miniPlayicon(){
        return this.playing ? 'icon-pause-mini' : 'icon-play-mini'
      },
      //唱片旋转
      cdCls(){
        return this.playing ? 'play' : 'play pause' 
      },
      disable() {
        return this.playReady ? '' : 'disbale'
      },
      //播放进度条设置
      precent() {
        return  this.currentTime / this.currentSong.duration
      },
    },
    methods:{
      //滑动进度条时 时间跟随改变
      slidingTimeChange(pre) {
        this.currentTime=pre* this.currentSong.duration
      },
      //播放器变小
      toMiniPlayer(){
        this.setFullscreen(false)
      },
      //播放器变大
      toMaxPlayer(){
        this.setFullscreen(true)
      },

      //滑动滚动条时，切换歌曲播放进度
      barPrecent(percent) {
        // console.log(percent)
        this.$refs.audio.currentTime  = percent * this.currentSong.duration 
        if(!this.playing){
          this.togglePlaying()
        }

        if( this.currentLyric ){
          this.currentLyric.seek(percent * this.currentSong.duration  *1000)
        }
      },
      //点击播放暂停按钮，改变播放状态
      togglePlaying(){
          this.setPlaying(!this.playing)
          if (this.currentLyric) {
            this.currentLyric.togglePlay()
          }
      },
      //当前歌曲播放到结尾时，继续播放下一首
      songEnded() {
        if(this.mode===playMode.loop){
          this.loop()
        }else{
          this.next()
        }
      },

      //循环播放
      loop() {
        this.$refs.audio.currentTime=0
        this.$refs.audio.play()
        if(this.currentLyric) {
          this.currentLyric.seek(0)
        }
      },
      //上一首
      prev() {
        //避免快速点击报错
        if(!this.playReady){
          return
        }
        //当前播放按钮为暂停样式时， 改变样式
        if(!this.playing){
          this.togglePlaying()
        }

        let index=this.currentIndex - 1
        //最后一首歌时切换到第一首
        if(index > this.playList.length){
          index=0
        }
        this.setCurrentIndex(index)

        this.playReady=false
      },
      //下一首
      next() {
        //避免快速点击报错
        if(!this.playReady){
          return
        }
        //当前播放按钮为暂停样式时， 改变样式
        if(!this.playing){
          this.togglePlaying()
        }
        if(this.playList===1){
          this.loop()
        } else {
          let index=this.currentIndex + 1
          if(index< 0){
            index=this.playList.length - 1
          } 
          this.setCurrentIndex(index)
        }
        
        this.playReady=false
      },
      ready() {
        this.playReady=true
        this.savePlayHistory(this.currentSong)
      },
      error() {
        this.playReady=true
      },
      updateTime(e){
        this.currentTime=e.target.currentTime
      },

      // 显示播放列表
      showPlayList() {
        this.$refs.playList.show()
      },
      //处理时间格式
      formatTime(interval) {
          interval=interval | 0
          let minite=interval / 60 | 0
          let second=this._pad(interval % 60 | 0)
          return `${minite}:${second}`
      },

      //处理歌词
      getLyric() {
        this.currentSong.getLyric().then(lyric=>{
            this.currentLyric = new Lyric(lyric, this.handleLyric)
            // console.log(this.currentLyric)
            if(this.playing) {
              this.currentLyric.play()
            }
        })
      },
      //歌词回调函数
      handleLyric({lineNum,txt}) {
        this.currentLineNum = lineNum
        if(lineNum >5 ) {
          let lineEl=this.$refs.lyricLine[lineNum-5]
          this.$refs.lyricList.scrollToElement(lineEl,1000)
        }else {
          this.$refs.lyricList.scrollTo(0,0,1000)
        }

        this.playingLyric=txt
      },
      //歌词切换动画
      middleTouchStart(e) {
         this.touch.initiated = true //初始化标志位
         this.touch.startX = e.touches[0].pageX
         this.touch.startY = e.touches[0].pageY
      },
      middleTouchMove(e) {
        if(!this.touch.initiated){
                 return 
         }

         const deltaX = e.touches[0].pageX-this.touch.startX
         const deltaY = e.touches[0].pageY-this.touch.startY
         //维护deltaY原因：歌词本身Y轴滚动，当|deltaY| > |deltaX|时，不滑动歌词
         if(Math.abs(deltaY) > Math.abs(deltaX)){ 
               return
         }
        
         const left = this.currentShow === 'cd' ? 0 : -window.innerWidth
        //  console.log(left)
         const offsetWidth = Math.min(0, Math.max(-window.innerWidth, left + deltaX))
        //  console.log(offsetWidth)
         this.touch.percent = Math.abs(offsetWidth / window.innerWidth)
        // console.log(offsetWidth+':'+this.touch.percent)
        //滑入歌词offsetWidth = 0 + deltaX(负值)  歌词滑出offsetWidth = -innerWidth + delta(正值)
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px, 0, 0)`
        
        //动画效果
        this.$refs.lyricList.$el.style[transitionDuration] = 0
        this.$refs.middleCD.style.opacity= 1 - this.touch.percent
        this.$refs.middleCD.style[transitionDuration] = 0
      },
      middleTouchEnd(e) {
        let offsetWidth    
        let opacity
        const time=400
       
        if(this.currentShow==='cd'){
          if(this.touch.percent > 0.1) {
            offsetWidth= -window.innerWidth
            this.currentShow='lyric'
            opacity= 0
          }else {
            offsetWidth = 0
            opacity =1
          }
        } else {
          if(this.touch.percent < 0.9 ){
            offsetWidth=0
            this.currentShow='cd'
            opacity =1
          }else {
            offsetWidth= -window.innerWidth
            opacity =0
          }
        }
        this.$refs.lyricList.$el.style[transform] = `translate3d(${offsetWidth}px, 0, 0)`
        //动画效果
        this.$refs.lyricList.$el.style[transitionDuration] = `${time}ms`
        this.$refs.middleCD.style.opacity= opacity
        this.$refs.middleCD.style[transitionDuration] = 0
      },
      //歌词切换动画
      ...mapActions([
        'savePlayHistory'
      ]),

      //事件格式
      _pad(num,n=2) {
        let len=num.toString().length
        while(len< n){
          num='0'+ num
          len++
        }
        return num
      },
      //切换 播放模式
      changeMode() {
        const mode =(this.mode+ 1) % 3
        this.setPlayMode(mode)
        let list=null
        if(mode===playMode.random){
          list=shuffle(this.sequenceList)
        }else{
          list=this.sequenceList
        }
        this.resetCurrentIndex(list)
        this.setPlayList(list)
      },
      
      // 播放器切换动画部分
      enter(el,done){
        const {x,y,scale} =this._getPosAndScale()
        let animation={
            // 第0帧的时候，先让图片缩小，显示在zuo下角
          0:{
            transform:`translate3d(${x}px,${y}px,0) scale(${scale})`
          },
          // 60%的时候，让图片回到cd中心，变大
          60:{
            transform:`translate3d(0,0,0) scale(1.3)`
          },
           // 变回原来的尺寸，会有一个回弹的效果
          100:{
            transform:`translate3d(0,0,0) scale(1)`
          },
        }
        //注册 动画
        animations.registerAnimation({
          name: 'move',
          animation,
          presets:{
            duration: 400,
            easing: 'linear'
          }
        }),
        
        animations.runAnimation(this.$refs.cdWrapper,'move',done)
      },
      afterEnter(){
        animations.unregisterAnimation('move')
        this.$refs.cdWrapper.style.animation= ''
      },
      leave(el,done){
        this.$refs.cdWrapper.style.transition='all 0.4s'
        const {x,y,scale} =this._getPosAndScale()
        this.$refs.cdWrapper.style[transform]=`translate3d(${x}px,${y}px,0) scale(${scale})`
        
        // 监听transitionend 事件在 CSS 完成过渡后触发done回调  
        this.$refs.cdWrapper.addEventListener('transitionend',done)
      },
      afterLeave(){
        this.$refs.cdWrapper.style.animation= ''
        this.$refs.cdWrapper.style[transform]= ''
      },
      _getPosAndScale(){ 
       const targetWidth = 40 //mini-player icon宽度
       const width = window.innerWidth * 0.8 //cd-wrapper宽度
       const paddingLeft = 40 
       const paddingTop = 80
       const paddingBottom = 30 //mini-player icon中心距底部位置
       const scale = targetWidth / width
       const x = -(window.innerWidth / 2 - paddingLeft) //X轴方向移动的距离
       const y = window.innerHeight - paddingTop - width / 2 - paddingBottom
        return {
              x,
              y, 
              scale
        }
      }
    },
    watch:{
        // 页面进来 播放歌曲
        currentSong(newSong,oldSong){
          if(!newSong.id){
            return
          }
          if(newSong.id===oldSong.id){
            return
          }
          // ∵ Lyric歌词前进时内部计时器控制 ∴切换歌曲时要清除计时器
          if(this.currentLyric){
            this.currentLyric.stop()
          }
          setTimeout(()=>{
              this.$refs.audio.play()
              this.getLyric()
          }, 1000)
        },
        //实际改变播放状态的还是播放器audio,监听playing
        playing(newVla){
          const audio =this.$refs.audio
          this.$nextTick(()=>{
            newVla ? audio.play() : audio.pause()
          })          
        }
    }
}
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .player
    .normal-player
      position: fixed
      left: 0
      right: 0
      top: 0
      bottom: 0
      z-index: 150
      background: $color-background
      .background
        position: absolute
        left: 0
        top: 0
        width: 100%
        height: 100%
        z-index: -1
        opacity: 0.6
        filter: blur(20px)
      .top
        position: relative
        margin-bottom: 25px
        .back
          position absolute
          top: 0
          left: 6px
          z-index: 50
          .icon-back
            display: block
            padding: 9px
            font-size: $font-size-large-x
            color: $color-theme
            transform: rotate(-90deg)
        .title
          width: 70%
          margin: 0 auto
          line-height: 40px
          text-align: center
          no-wrap()
          font-size: $font-size-large
          color: $color-text
        .subtitle
          line-height: 20px
          text-align: center
          font-size: $font-size-medium
          color: $color-text
      .middle
        position: fixed
        width: 100%
        top: 80px
        bottom: 170px
        white-space: nowrap
        font-size: 0
        .middle-l
          display: inline-block
          vertical-align: top
          position: relative
          width: 100%
          height: 0
          padding-top: 80%
          .cd-wrapper
            position: absolute
            left: 10%
            top: 0
            width: 80%
            height: 100%
            .cd
              width: 100%
              height: 100%
              box-sizing: border-box
              border: 10px solid rgba(255, 255, 255, 0.1)
              border-radius: 50%
              &.play
                animation: rotate 20s linear infinite
              &.pause
                animation-play-state: paused
              .image
                position: absolute
                left: 0
                top: 0
                width: 100%
                height: 100%
                border-radius: 50%

          .playing-lyric-wrapper
            width: 80%
            margin: 30px auto 0 auto
            overflow: hidden
            text-align: center
            .playing-lyric
              height: 20px
              line-height: 20px
              font-size: $font-size-medium
              color: $color-text-l
        .middle-r
          display: inline-block
          vertical-align: top
          width: 100%
          height: 100%
          overflow: hidden
          .lyric-wrapper
            width: 80%
            margin: 0 auto
            overflow: hidden
            text-align: center
            .text
              line-height: 32px
              color: $color-text-l
              font-size: $font-size-medium
              &.current
                color: $color-text
      .bottom
        position: absolute
        bottom: 50px
        width: 100%
        .dot-wrapper
          text-align: center
          font-size: 0
          .dot
            display: inline-block
            vertical-align: middle
            margin: 0 4px
            width: 8px
            height: 8px
            border-radius: 50%
            background: $color-text-l
            &.active
              width: 20px
              border-radius: 5px
              background: $color-text-ll
        .progress-wrapper
          display: flex
          align-items: center
          width: 80%
          margin: 0px auto
          padding: 10px 0
          .time
            color: $color-text
            font-size: $font-size-small
            flex: 0 0 30px
            line-height: 30px
            width: 30px
            &.time-l
              text-align: left
            &.time-r
              text-align: right
          .progress-bar-wrapper
            flex: 1
        .operators
          display: flex
          align-items: center
          .icon
            flex: 1
            color: $color-theme
            &.disable
              color: $color-theme-d
            i
              font-size: 30px
          .i-left
            text-align: right
          .i-center
            padding: 0 20px
            text-align: center
            i
              font-size: 40px
          .i-right
            text-align: left
          .icon-favorite
            color: $color-sub-theme
      &.normal-enter-active, &.normal-leave-active
        transition: all 0.4s
        .top, .bottom
          transition: all 0.4s cubic-bezier(0.86, 0.18, 0.82, 1.32)
      &.normal-enter, &.normal-leave-to
        opacity: 0
        .top
          transform: translate3d(0, -100px, 0)
        .bottom
          transform: translate3d(0, 100px, 0)
    .mini-player
      display: flex
      align-items: center
      position: fixed
      left: 0
      bottom: 0
      z-index: 180
      width: 100%
      height: 60px
      background: $color-highlight-background
      &.mini-enter-active, &.mini-leave-active
        transition: all 0.4s
      &.mini-enter, &.mini-leave-to
        opacity: 0
      .icon
        flex: 0 0 40px
        width: 40px
        padding: 0 10px 0 20px
        img
          border-radius: 50%
          &.play
            animation: rotate 10s linear infinite
          &.pause
            animation-play-state: paused
      .text
        display: flex
        flex-direction: column
        justify-content: center
        flex: 1
        line-height: 20px
        overflow: hidden
        .name
          margin-bottom: 2px
          no-wrap()
          font-size: $font-size-medium
          color: $color-text
        .desc
          no-wrap()
          font-size: $font-size-small
          color: $color-text-d
      .control
        flex: 0 0 30px
        width: 30px
        padding: 0 10px
        .icon-play-mini, .icon-pause-mini, .icon-playlist
          font-size: 30px
          color: $color-theme-d
        .icon-mini
          font-size: 32px
          position: absolute
          left: 0
          top: 0

  @keyframes rotate
    0%
      transform: rotate(0)
    100%
      transform: rotate(360deg)
</style>